﻿namespace Jsl.FxCop
{
    using System;
    using Microsoft.FxCop.Sdk;

    /// <summary>
    /// Finds a number of different type casting issues.
    /// </summary>
    public class TypecastingProblems : BaseIntrospectionRule
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="TypecastingProblems"/> class.
        /// </summary>
        public TypecastingProblems()
            : base(typeof(TypecastingProblems).Name, "Jsl.FxCop.Rules", typeof(TypecastingProblems).Assembly)
        {
        }
        #endregion Constructors

        #region Public Methods
        /// <summary>
        /// Checks the specified member.
        /// </summary>
        /// <param name="member">The member to check.</param>
        /// <returns>The problems found, if any.</returns>
        public override ProblemCollection Check(Member member)
        {
            // We only care about methods.
            var method = member as Method;
            if (method == null)
            {
                return this.Problems;
            }

            this.Visit(method);

            return this.Problems;
        }

        /// <summary>
        /// Visits the method call.
        /// </summary>
        /// <param name="call">The call to visit.</param>
        public override void VisitMethodCall(MethodCall call)
        {
            if (call == null)
            {
                throw new ArgumentNullException("call");
            }

            var calledMethod = call.GetMethod();

            if (calledMethod.DeclaringType.FullName == WellKnownTypeNames.Type)
            {
                switch (calledMethod.Name.Name)
                {
                    case "GetType":
                        // GetType() is OK, but the ones that take parameters are all bad!
                        if (calledMethod.Parameters.Count > 0)
                        {
                            // See if we can get the string constant, if any, that is being used.
                            string typeName;
                            if (call.Operands[0].TryGetLiteral(out typeName))
                            {
                                this.Problems.Add(new Problem(this.GetNamedResolution("UseTypeOfWithName", typeName), calledMethod));
                            }
                        }

                        break;

                    case "GetInterface":
                        string interfaceName;
                        if (call.Operands[0].TryGetLiteral(out interfaceName))
                        {
                            this.Problems.Add(new Problem(this.GetNamedResolution("UseAsWithName", interfaceName), calledMethod));
                        }

                        break;
                }
            }

            base.VisitMethodCall(call);
        }
        #endregion Public Methods
    }
}